package com.springboot2.service.Impl;

import com.springboot2.entity.Org;
import com.springboot2.mapper.OrgMapper;
import com.springboot2.service.OrgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class OrgServiceImpl implements OrgService {

    @Resource
    private OrgMapper orgMapper;

    @Override
    public void add(Org org) {
        orgMapper.add(org);
    }

    @Override
    public void del(int id) {
        orgMapper.del(id);
    }

    @Override
    public void update(Org org) {
        orgMapper.update(org);
    }

    @Override
    public Org findById(int id) {
        return orgMapper.findById(id);
    }

    @Override
    public List<Org> findAll() {
        //  生成树状数据结构
        List<Org> list = orgMapper.findAll();

        return childrenTree(null,list);
    }

    @Override
    public int count() {
        return orgMapper.count();
    }

    @Override
    public List<Org> findByName(String name) {
        return orgMapper.findByName(name+"%");
    }

    //递归生成 树状结构
    private List<Org> childrenTree(Integer pid,List<Org> allData){
        List<Org> list = new ArrayList<>();
        //org.getPid() == pid
        for (Org org : allData) {
            if(Objects.equals(org.getPid(),pid)){
                list.add(org);
                List<Org> childrenTree = childrenTree(org.getId(),allData);
                org.setChildren(childrenTree);

            }
        }

        return list;
    }
}
